﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Arroguella.Utilities
{
    /// <summary>
    /// A RandomChooser class defines an object responsible for maintaining a collection of other objects, 
    /// and being able to choose one at random.
    /// </summary>
    public class RandomChooser<T>
    {
        #region Constructors

        public RandomChooser(ICollection<T> collection)
        {
            Debug.Assert(collection != null, "A collection in RandomChooser is null.");
            this.collection = collection;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Chooses one of the elements within its collection at random, and returns it.
        /// This does not remove the element from the list.
        /// </summary>
        public virtual T Choose()
        {
            int index = random.Next(0, collection.Count);
            return collection.ElementAt(index);
        }

        /// <summary>
        /// Chooses one of the elements within its collection at random, and returns its ToString() method.
        /// This does not remove the element from the list.
        /// </summary>
        public virtual string ChooseAsString()
        {
            return Choose().ToString();
        }

        public void Add(T value)
        {
            collection.Add(value);
        }

        public void Add(ICollection<T> values)
        {
            foreach (T value in values)
            {
                collection.Add(value);
            }
        }

        public void Remove(T value)
        {
            collection.Remove(value);
        }

        #endregion

        #region Properties

        private readonly ICollection<T> collection;

        private readonly Random random = new Random();

        #endregion
    }
}
